package com.libhttp

import rxhttp.wrapper.annotation.Parser
import rxhttp.wrapper.exception.ParseException
import rxhttp.wrapper.parse.TypeParser
import rxhttp.wrapper.utils.convertTo
import java.io.IOException
import java.lang.reflect.Type

/**
 * Created on 2022/9/8.
 * @author Joker
 * Des:
 */

@Parser(name = "ResponseData")
open class ResponseParser<T> : TypeParser<T> {

    protected constructor() : super()

    constructor(type: Type) : super(type)

    @Throws(IOException::class)
    override fun onParse(response: okhttp3.Response): T? {
        val responseBean: ResponseBean<T> = response.convertTo(ResponseBean::class, *types)
        HttpManager.serverTime = responseBean.serverTime
        val code = responseBean.code
        var data = responseBean.data
        val msg = responseBean.message

        if (code == 200 && types[0] === Any::class.java) {
            data = null //返回空的对象
        }

        when {
            //处理正常非200业务
            code != 200 -> throw ParseException(code.toString(), msg, response)

            //处理返回200无法解析data泛型的
            code == 200 && data == null -> throw ParseException(code.toString(), msg, response)
        }

        return data
    }
}